<template>
  <div>
    <el-dialog :title="roleForm.id?'编辑角色':'新增角色'" :visible="addVisible" @close="closeRoleDialog">
      <!-- 表单内容 -->
      <el-form ref="roleForm" :model="roleForm" :rules="rules" label-width="100px">
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="roleForm.name" />
        </el-form-item>
        <el-form-item label="角色描述" prop="description">
          <el-input v-model="roleForm.description" />
        </el-form-item>
      </el-form>
      <!-- 底部 -->
      <el-row slot="footer" type="flex" justify="center">
        <el-button size="small" @click="closeRoleDialog">取消</el-button>
        <el-button size="small" type="primary" @click="submit">确定</el-button>
      </el-row>
    </el-dialog>
  </div>
</template>
<script>
import { addRole, getRoleDetail, updateRole } from '@/api/setting'
export default {
  name: 'AddRole',
  props: {
    addVisible: {
      type: Boolean
    }
  },
  data() {
    return {
      roleForm: {
        name: '',
        description: ''
      },
      rules: {
        name: [{ required: true, message: '角色名称不能为空', trigger: 'blur' }],
        description: [{ required: true, message: '角色描述不能为空', trigger: 'blur' }]
      }
    }
  },
  methods: {
    // 关闭弹窗
    closeRoleDialog() {
      this.$emit('close-dialog')
      this.resetForm()
    },
    submit() {
      // 兜底校验
      this.$refs.roleForm.validate(async valid => {
        if (valid) {
          if (this.roleForm.id) {
            await updateRole(this.roleForm)
          } else {
            await addRole(this.roleForm)
          }
          this.$message.success(`${this.roleForm.id ? '编辑' : '新增'}成功`)
          // 关闭弹窗
          this.closeRoleDialog()
          // 更新列表
          this.$emit('fetch-role-list')
          // 清空列表
          this.resetForm()
        }
      })
    },
    async editRole(id) {
      const res = await getRoleDetail(id)
      this.roleForm = res
    },
    resetForm() {
      this.roleForm =
      { name: '',
        description: ''
      }
      this.$refs.roleForm.resetFields()
    }

  }
}
</script>
